package com.ust.app.movie.service.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.ust.app.movie.entity.User;
import com.ust.app.movie.service.LoginService;

public class LoginServiceImpl implements LoginService{

	private SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public User authenticate(String username, String password) throws Exception{
		
		// get current session
		Session session = this.sessionFactory.getCurrentSession();
		
		// begin a transaction
		session.beginTransaction();
		
		// create a query
		Query query = session.createQuery("from User u where u.username = :username " +
				"and password = :password");
		query.setParameter("username", username);
		query.setParameter("password", password);
		
		@SuppressWarnings("unchecked")
		List<User> userList = query.list();
		
		// commit transaction
		session.getTransaction().commit();
		
		if(userList == null){
			return null;
		}
		
		if((userList.size() > 1) || (userList.size() == 0)){
			return null;
		}
		
		return userList.get(0);
		
	}
	
	

}
